#include "stdafx.h"
#include "LayoutGroup.h"
#include "FakeNode.h"

namespace fusion
{
    namespace mode10
    {
        /*
         * LayoutBase
         */
        LayoutGroup::LayoutGroup(Node* node,  Ref<BaseLayoutParams> params):
			LayoutNode(node, params)
        {

		};
        LayoutGroup::~LayoutGroup() {};

		//bool LayoutGroup::IsLayoutable() { return true; }

		Ref<BaseLayoutParams> LayoutGroup::GenerateLayoutParams(const Ref<ClientParamsAdapter>& params)
		{
			return onGenerateLayoutParams(params);
		}

		bool LayoutGroup::AddLayoutNode(const Ref<LayoutNode> child)
		{
			if (child.get() == this )
			{
				// show error
				return false;
			}
			return onAddLayoutNode(child);
		}

		bool LayoutGroup::RemoveLayoutNode(Ref<LayoutNode> child)
		{
			if (child.get() == this )
			{
				// show error
				return false;
			}
			return onRemoveLayoutNode(child);
		}

		void LayoutGroup::RemoveAllChild()
		{
			for (List<Ref<LayoutNode> >::iterator iter = m_Nodes.begin(); iter != m_Nodes.end(); ++iter)
			{
				if ((*iter)->IsLayoutable())
				{
					Ref<LayoutNode> node = (*iter);
					Ref<LayoutGroup> group = dynamic_cast<LayoutGroup*>( node.get() );
					group->RemoveAllChild();
				}
				(*iter)->SetParent(NULL);
				(*iter)->GetNode()->SetRelatedLayout(NULL);			
			}
			m_Nodes.clear();
		}

		// ok, how to generate
		Ref<BaseLayoutParams> LayoutGroup::onGenerateLayoutParams(const Ref<ClientParamsAdapter>& params)
		{
			return new BaseLayoutParams(params->GetWidth(), params->GetHeight());
		}

		Ref<BaseLayoutParams> LayoutGroup::GetDefaultParams(const Node* node)
		{
			return new BaseLayoutParams(node->sizeX, node->sizeY);
		}

		bool LayoutGroup::onAddLayoutNode(const Ref<LayoutNode> child)
		{
			if (!child) 
				return false;

			m_Nodes.push_back(child);
			child->SetParent(this);
			return true;
		}

		bool LayoutGroup::onRemoveLayoutNode(Ref<LayoutNode> child)
		{
			if (!child)
				return false;

			for (List<Ref<LayoutNode> >::iterator iter = m_Nodes.begin(); iter != m_Nodes.end(); ++iter)
			{
				if ( (*iter) == child )
				{
					if ( (*iter)->IsLayoutable() )
					{
						Ref<LayoutNode> node = (*iter);
						Ref<LayoutGroup> group = dynamic_cast<LayoutGroup*>(node.get() );
						group->RemoveAllChild();
					}
					(*iter)->SetParent(NULL);
					(*iter)->GetNode()->SetRelatedLayout(NULL);
					m_Nodes.erase(iter);
					return true;
				}
			}
			return false;
		}
    }
}
